package cn.ecnu.controller;

import cn.ecnu.dao.OrderDao;
import cn.ecnu.entity.Employee;
import cn.ecnu.entity.Order;

import cn.ecnu.feign.ManagementFeignService;
import cn.ecnu.utils.R;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RefreshScope
@RestController
@RequestMapping("/order")
public class ManagementController {

    @Resource
    private OrderDao orderDao;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ManagementFeignService managementFeignService;

    @GetMapping("/getProper/{target}/{oid}")
    public R getProperCouriers(@PathVariable("oid") String oid, @PathVariable("target") String target) {
        try {
            Order order = orderDao.getOrderByOid(oid);
            //得到订单目前所处的城市
            String location = order.getRoute().split("\\|")[order.getCurrentIndex()];
            R r = null;
            if (target.equals("快递员")) {
                r = managementFeignService.getEmployeeByLocation(location);
            } else if (target.equals("运输员")) {
                //得到订单的目的地
                String destination = order.getRoute().split("\\|")[order.getCurrentIndex() + 1];
                R temp = managementFeignService.getTransmissionByLocation(location);
                List<Map> employees = (List<Map>) temp.get("data");
                ArrayList<Map> res = new ArrayList<>();
                for (Map employee : employees) {
                    String key = employee.get("id") + "_dst";
                    if (redisTemplate.hasKey(key)) {
                        String dst = (String) redisTemplate.opsForValue().get(key);
                        if (dst.equals(destination)) {
                            res.add(employee);
                        }
                    } else {
                        res.add(employee);
                    }
                }
                r = R.ok().put("data", res);
            } else if (target.equals("车辆")) {
                r = managementFeignService.getCarByLocation(location);
            }
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("未知错误");
        }
    }
}

